package com.jtzc.mcp.csdn;

import com.jtzc.mcp.csdn.domain.service.CSDNArticleService;
import com.jtzc.mcp.csdn.infrastructure.gateway.ICSDNService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;


@Slf4j
@SpringBootApplication
public class McpServerApplication {

    public static void main(String[] args) {
        // 解析命令行参数中的cookie
        String cookieArg = null;
        for (int i = 0; i < args.length; i++) {
            if ("--cookie".equals(args[i]) && i + 1 < args.length) {
                cookieArg = args[i + 1];
                break;
            } else if (args[i].startsWith("--cookie=")) {
                cookieArg = args[i].substring("--cookie=".length());
                break;
            }
        }

        // 如果命令行传入了cookie，设置为系统属性
        if (cookieArg != null && !cookieArg.trim().isEmpty()) {
            System.setProperty("csdn.api.cookie", cookieArg);
            log.info("使用命令行传入的cookie进行CSDN认证");
        }

        SpringApplication.run(McpServerApplication.class, args);
    }
    /**
     * 创建csdn 接口的代理实现
     */

    @Bean
    public ICSDNService csdnService() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://bizapi.csdn.net/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(ICSDNService.class);
    }

    /**
     * 暴露tools
     */
    @Bean
    public ToolCallbackProvider csdnTools(CSDNArticleService csdnArticleService) {
        return MethodToolCallbackProvider.builder().toolObjects(csdnArticleService).build();
    }

}
